package com.un.ebs.customer.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.un.ebs.core.exception.BusinessEntityNotFoundException;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.util.SecurityUtils;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.core.util.WebResult;
import com.un.ebs.core.util.WebUtils;
import com.un.ebs.customer.domain.Customer;
import com.un.ebs.customer.domain.CustomerAndDefunctExt;
import com.un.ebs.customer.domain.DefunctExt;
import com.un.ebs.customer.dto.DefunctAddDto;
import com.un.ebs.customer.dto.DefunctUpdateDto;
import com.un.ebs.customer.dto.DefunctVo;
import com.un.ebs.customer.service.CustomerService;
import com.un.ebs.customer.service.CustomerTraceService;
import com.un.ebs.customer.service.DefunctService;
import com.un.ebs.customer.vo.CustomerSimpleVo;
import com.un.ebs.customer.vo.DefunctDetailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liubo
 * @since 2019-09-24
 */
@RestController
@RequestMapping("/defunct")
@Api(value = "defunct", description = "")
public class DefunctController {

    @Autowired
    private DefunctService service;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CustomerTraceService customerTraceService;

    @PostMapping("add")
    @ApiOperation(value = "add", notes = "添加")
    public WebResult save(@RequestBody @Validated DefunctAddDto req) {
        service.add(req);
        return WebUtils.success();
    }

    @PostMapping("update")
    @ApiOperation(value = "update", notes = "修改")
    public WebResult update(@RequestBody @Validated DefunctUpdateDto req) {
        service.update(req);
        return WebUtils.success();
    }

    @PostMapping("bind")
    @ApiOperation(value = "绑定，客户与使用者绑定", notes = "修改")
    public WebResult bind(@RequestParam String customerId, @RequestParam String defunctId) {
        service.bind(customerId, defunctId);
        return WebUtils.success();
    }

    @PostMapping("bindByUser")
    @ApiOperation(value = "绑定，客户与使用者绑定", notes = "修改")
    public WebResult bindByUser(@RequestParam String defunctId) {
        Customer customer = customerService.queryByUserId(SecurityUtils.getUserContent().getId());
        if (customer == null) {
            throw new BusinessException("你的账号类型异常，无法完成与墓位使用者的绑定。");
        }
        service.bind(customer.getId(), defunctId);
        return WebUtils.success();
    }

    @GetMapping("detail/{id}")
    @ApiOperation(value = "getViewById", notes = "根据主键获取单个 Defunct")
    public WebResult<DefunctDetailVo> getViewById(@PathVariable("id") String id) {
        DefunctDetailVo result = new DefunctDetailVo();
        DefunctExt defunct = service.queryViewById(id);
        if (defunct == null) {
            throw new BusinessEntityNotFoundException(id, "逝者");
        }
        BeanUtils.copyProperties(defunct, result);

        List<CustomerAndDefunctExt> customerAndDefunctExts = customerService.queryCustAndDefunctByDefunctId(id);
        List<String> custIds = customerAndDefunctExts.stream().map((s -> s.getCustomerId())).distinct().collect(Collectors.toList());
        result.setTraceList(customerTraceService.queryByCustId(custIds));
        result.setOrderList(customerService.queryOrderByDefunctId(id));

        result.setCustList(customerAndDefunctExts.stream().map(s -> {
            CustomerSimpleVo simpleVo = new CustomerSimpleVo();
            simpleVo.setId(s.getCustomerId());
            simpleVo.setName(s.getCustName());
            simpleVo.setPhone(s.getCustPhone());
            return simpleVo;
        }).distinct().collect(Collectors.toList()));

        result.setAttrList(service.queryAttrs(id));
        return WebUtils.success(result);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "getById", notes = "根据主键获取单个 Defunct")
    public WebResult<DefunctVo> getById(@PathVariable("id") String id) {
        return WebUtils.success(service.queryViewById(id));
    }

    @GetMapping("/listByUserId")
    @ApiOperation(value = "查询逝者，根据当前用户")
    public WebResult<List<DefunctExt>> listByUserId(@RequestParam(required = false) String userId) {
        return WebUtils.success(service.queryByUserId(StringUtils.isNullOrEmpty(userId) ? SecurityUtils.getUserContent().getId() : userId));
    }

    @GetMapping("/listByTombSkuId")
    @ApiOperation(value = "根据墓位的SKUID查询逝者")
    public WebResult<List<DefunctExt>> listByTombSkuId(@RequestParam String id) {
        return WebUtils.success(service.queryByTombSkuId(id));
    }

    @GetMapping("list")
    @ApiOperation(value = "查询逝者", notes = "")
    public WebResult<IPage<DefunctExt>> list(@RequestParam(required = false) String searchText, @RequestParam(required = false) @ApiParam("是否已下葬") Boolean isBury, @RequestParam Integer pageIndex, @RequestParam Integer pageSize) {
        //return WebUtils.success(service.query(searchText, isBury, pageIndex, pageSize));
        return WebUtils.success(service.queryByCustomer(searchText, pageIndex, pageSize));
    }

    @PostMapping("delete/{id}")
    @ApiOperation(value = "delete", notes = "根据主键删除单个 Defunct")
    public WebResult delete(@PathVariable("id") String id) {
        service.delete(id);
        return WebUtils.success();
    }

}